//
//  HomeViewModel.swift
//  SwiftUI+MVVM+Repository
//
//  Created by 高强 on 2024/9/24.
//

import Foundation
import Combine

class NewsItemViewModel: ObservableObject {
    
    @Published var newsItems: [NewsBean] = []
    @Published var errorMessage: String = ""
    @Published var showError: Bool = false
    @Published var pageNum: Int = 1
    @Published var total: Int = 0
    let pageSize = 10
    let type = "0"
    
    @Published var isLoadingMore: Bool = false
    
    private var repository = NewsRepository()
    private var cancellables = Set<AnyCancellable>()
    
    // 首次加载/下拉刷新
    func fetchNews() {
        pageNum = 1
        repository.newsList(pageNum: pageNum, pageSize: pageSize, type: type)
            .sink(receiveCompletion: { completion in
                switch completion {
                    case .finished:
                        break
                    case .failure(let error):
                        self.errorMessage = error.localizedDescription
                        self.showError = true
                }
            }, receiveValue: { response in
                self.total = response.total
                self.newsItems = response.rows
            })
            .store(in: &cancellables)
    }
    
    // 上拉加载更多
    func loadMoreNews() {
        guard !isLoadingMore else { return } // 防止重复加载
        
        guard (newsItems.count < total) else {return} //如果item个数已经等于总个数，则不允许下拉更多了
        
        isLoadingMore = true
        pageNum += 1
        
        repository.newsList(pageNum: pageNum, pageSize: pageSize, type: type)
            .sink(receiveCompletion: { completion in
                switch completion {
                    case .finished:
                        self.isLoadingMore = false
                    case .failure(let error):
                        self.errorMessage = error.localizedDescription
                        self.showError = true
                        self.isLoadingMore = false
                }
            }, receiveValue: {response in
                self.newsItems.append(contentsOf: response.rows) // 将新数据追加到当前列表中
            })
            .store(in: &cancellables)
        
    }
}
